/*
创建时间: 2021/1/10 17:05
作者: zjy
功能介绍:

*/

package apis

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"os"
	"path/filepath"
)

var JsonCfgMap map[string]string

func init() {
	JsonCfgMap = make(map[string]string)
}
func LoadVersion() {
	jsonfile, erro := os.Open("version.json")
	if erro != nil {
		fmt.Println(erro)
		return
	}
	jsond := json.NewDecoder(jsonfile)
	if jsond == nil {
		fmt.Printf("json decoder 失败")
		return
	}
	jsond.Decode(&serverinfo)
}

// 重新加载
func RLoadVersion(c *gin.Context) {
	LoadVersion()
	c.JSON(http.StatusOK, serverinfo)
}

func GetServerInfo(c *gin.Context) {
	c.JSON(http.StatusOK, serverinfo)
}

// 登录服上传信息
func UploadLogin(c *gin.Context) {

	//验证ip地址
	fmt.Println(c.Request.RemoteAddr)

	var login = new(UploadLoinInfo)
	if erro := c.ShouldBind(login); erro != nil {
		c.JSON(http.StatusOK, &gin.H{
			"msg": "上传数据失败",
		})
		return
	}
	switch login.UploadType {
	case Upload_OnLine, Upload_Offline:
		setLoginInfo(login)
		break
	case Upload_Num:
		if !setUserNum(c, login) {
			return
		}
		break
	}

	c.JSON(http.StatusOK, &gin.H{
		"msg": "上传数据成功",
	})
}

// 设置用户信息
func setUserNum(c *gin.Context, login *UploadLoinInfo) bool {
	if LoginServer == nil {
		c.JSON(http.StatusOK, &gin.H{
			"msg": "请求数据有误",
		})
		return false
	}
	var isFind bool
	svlen := len(LoginServer)
	for i := 0; i < svlen; i++ {
		ls := LoginServer[i]
		if ls.Ip == login.LoginInfo.Ip && ls.Port == login.LoginInfo.Port {
			ls.Num = login.LoginInfo.Num
			isFind = true
		}
	}

	if !isFind {
		c.JSON(http.StatusOK, &gin.H{
			"msg": "请求数据有误",
		})
		return false
	}
	return true
}

func setLoginInfo(login *UploadLoinInfo) {
	if LoginServer == nil {
		LoginServer = append(LoginServer, login.LoginInfo)
		return
	}
	var isFind bool
	for _, ls := range LoginServer {
		if ls.Ip == login.LoginInfo.Ip && ls.Port == login.LoginInfo.Port {
			ls.Num = login.LoginInfo.Num
			ls.Status = login.LoginInfo.Status
			isFind = true
		}
	}

	if !isFind {
		LoginServer = append(LoginServer, login.LoginInfo)
	}

}

// 主界面
func Home(c *gin.Context) {
	//验证ip地址
	c.HTML(http.StatusOK, "HomePage.tmpl", gin.H{
		"title": "zjy学习",
	})
}

func LoadJsonCfg(c *gin.Context) {
	filepath.Walk(GAppInfo.JsonCfgPath, WalkOneFile)
	marshal, err := json.Marshal(JsonCfgMap)
	if err != nil {
		c.JSON(http.StatusOK, &gin.H{
			"msg": err.Error(),
		})
		return
	}
	c.JSON(http.StatusOK, &gin.H{
		"msg": string(marshal),
	})
}
